package logic

import (
	"common/globals"
	"common/model"
	"context"
	"encoding/json"
	"errors"
	mealProduct "meal_products_srv/proto"
	"time"
)

func (m *MealProductServer) MealProductList(ctx context.Context, req *mealProduct.MealProductListRequest) (*mealProduct.MealProductListResponse, error) {
	var userinfo model.User
	err := userinfo.GetUserInfoById(int(req.Userid))
	if err != nil {
		return nil, err
	}
	if userinfo.ID == 0 {
		return nil, errors.New("请重新登录")
	}
	if req.Classification != "" && req.Classification != "精品推荐" && req.Classification != "人气热卖" && req.Classification != "精选套餐" {
		return nil, errors.New("请传递合适的筛选范围")
	}
	if req.Classification != "" {
		hobbyAdd := model.UserHobby{
			UserId: int(req.Userid),
			Hobby:  req.Classification,
		}
		err = hobbyAdd.Create()
		if err != nil {
			return nil, err
		}
	} else {
		hobbyAdd := model.UserHobby{
			UserId: int(req.Userid),
			Hobby:  "所有",
		}
		err = hobbyAdd.Create()
		if err != nil {
			return nil, err
		}
	}
	redisKey := "MealProduct:" + req.Classification
	result, _ := globals.Rdb.Get(ctx, redisKey).Result()
	var mealProductList []*mealProduct.MealProductListInfo
	if result == "" {
		var mealProducts model.MealProduct
		res, err := mealProducts.GetAllMealProductByClassification(req.Classification)
		if err != nil {
			return nil, err
		}
		if len(res) == 0 {
			return nil, errors.New("暂时没有餐品推荐")
		}
		for _, v := range res {
			mealProductList = append(mealProductList, &mealProduct.MealProductListInfo{
				MealProductName:  v.MealProductName,
				MealProductPrice: float32(v.MealProductPrice),
				Image:            v.Image,
				Classification:   v.Classification,
			})
		}
		marshal, err := json.Marshal(&mealProductList)
		if err != nil {
			return nil, err
		}
		err = globals.Rdb.Set(ctx, redisKey, string(marshal), time.Hour*3).Err()
		if err != nil {
			return nil, err
		}
		return &mealProduct.MealProductListResponse{AllMealProduct: mealProductList}, nil
	} else {
		err = json.Unmarshal([]byte(result), &mealProductList)
		if err != nil {
			return nil, err
		}
		return &mealProduct.MealProductListResponse{AllMealProduct: mealProductList}, nil
	}
}
